package com.mipo.shiro;

import java.util.Arrays;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

public class RoleTest {
    @Test
    public void testHasRole() {
        Subject currentUser = login("classpath:shiro.ini", "csdn2", "123");
        boolean a1 = currentUser.hasRole("role2"); // 返回true。是否有role2这个角色
        boolean[] a2 = currentUser.hasRoles(Arrays.asList("role1","role2","role3")); // 返回[true,true,false]。是否有对应的角色
        boolean a3 = currentUser.hasAllRoles(Arrays.asList("role1","role2","role3")); // 抛异常。有一个不存在则抛异常，都存在则返回true
        currentUser.getPrincipal();//用户名
        System.out.println(a1);
        System.out.println(a2);
        System.out.println(a3);
        currentUser.logout();
    }
    @Test
    public void testCheckRole() {
        Subject currentUser = login("classpath:shiro.ini", "csdn2", "123");
        currentUser.checkRole("role3"); // 没有返回值。有就不报错，没有就会报错
        currentUser.checkRoles(Arrays.asList("role1","role2","role3")); // 没有返回值。有就不报错，没有就会报错
        currentUser.checkRoles(Arrays.asList("role1","role3")); // 没有返回值。有就不报错，没有就会报错
        currentUser.logout();
    }
    
    public Subject login(String configFile, String username, String password) {
		Factory<SecurityManager> factory = new IniSecurityManagerFactory(configFile); // 读取配置文件，初始化SecurityManager工厂
		SecurityManager securityManager = factory.getInstance(); // 获取securityManager实例
		SecurityUtils.setSecurityManager(securityManager); // 把securityManager实例绑定到SecurityUtils
		Subject currentUser = SecurityUtils.getSubject(); // 得到当前执行的用户
		UsernamePasswordToken token = new UsernamePasswordToken(username, password); // 创建token令牌，用户名/密码
		try {
			System.out.println("身份认证成功！");
			currentUser.login(token); // 身份认证
		} catch (AuthenticationException e) {
			System.out.println("身份认证失败！");
			e.printStackTrace();
		}
		return currentUser;
    }
    
    
}